<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard\Detail;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ChannelCode\Logic\ContactLogic;

/**
 * 企业联系人.
 * @Controller
 */
class Contact extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     *
     * @RequestMapping(path="/dashboard/client/detail/contact", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 请求参数
        $params = $this->request->inputs(
            ['clientId'],
        );
        // 校验参数
        $this->validated($params);
        $params['user'] = $user;
      return Db::table('client_contact_pivot as pivot')->where('pivot.client_id',$params['clientId'])
            ->leftJoin('work_contact as contact','contact.id','=','pivot.contact_id')
            ->leftJoin('work_contact_employee as employee_pivot','employee_pivot.contact_id','=','pivot.contact_id')
            ->leftJoin('work_employee as employee','employee.id','=','employee_pivot.employee_id')
            ->leftJoin('contact_follow as follow','follow.contact_id','=','pivot.contact_id')
            ->select([
                'contact.name as userInfo',//联系人名称
                'employee.name as employee',//员工名称
                Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(mc_follow.created_at ORDER BY mc_follow.id DESC SEPARATOR ","),",",1) AS lastMessageTime'),//最后跟进时间
                'pivot.created_at as createdAt',//绑定时间
            ])
            ->groupBy(['pivot.contact_id'])
            ->get()->toArray();
        return $this->container->get(ContactLogic::class)->handle($params);
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'clientId' => 'integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'clientId.integer' => '客户ID必须为整数',
        ];
    }
}
